package com.ktg.ktgcommon.aop;

import com.ktg.ktgcommon.result.CodeEnum;
import com.ktg.ktgcommon.result.R;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.stream.Stream;

@Component
@Aspect
public class SysAspect {
    @Around("@annotation(sb)")
    public Object checkPermission(ProceedingJoinPoint joinPoint, SecuredOperation sb) throws Throwable {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new AccessDeniedException("User is not authenticated");
        }

        Stream<String> requiredAuthorities = Arrays.stream(sb.value());
        boolean hasPermission = requiredAuthorities.anyMatch(auth ->
                authentication.getAuthorities().stream()
                        .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(auth))
        );

        if (!hasPermission) {
            return R.FAIL(CodeEnum.user_qx);
        }
        return joinPoint.proceed();
    }
}
